package cn.itmantzy.pet.service.impl;


import cn.itmantzy.basic.service.impl.BaseServiceImpl;
import cn.itmantzy.pet.domain.Pet;
import cn.itmantzy.pet.domain.PetDetail;
import cn.itmantzy.pet.mapper.PetDetailMapper;
import cn.itmantzy.pet.mapper.PetMapper;
import cn.itmantzy.pet.service.IPetService;
import cn.itmantzy.user.domain.Logininfo;
import cn.itmantzy.user.domain.User;
import cn.itmantzy.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(Pet pet){
        petMapper.save(pet); // 返回自增id
        PetDetail detail = pet.getDetail();
        // 判断细节是否为空，前端用户可能不会在处理时编辑细节，所以可能为空
        if(detail != null){
            detail.setPet_id(pet.getId());
            petDetailMapper.save(detail);
        }
    }

    @Override
    public void onSale(List<Long> ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("onsaleTime", new Date());
        petMapper.onSale(map);
    }

    @Override
    public void offSale(List<Long> ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("offsaleTime", new Date());
        petMapper.offSale(map);
    }

    @Override
    public Pet queryByIdDetail(Long id) {
        return petMapper.loadByIdDetail(id);
    }

    @Override
    public void adopt(Long id, Logininfo logininfo) {
        // 查询出宠物信息
        Pet pet = petMapper.loadById(id);
        // 1.下架宠物
        pet.setState(0);
        // 设置下架时间
        pet.setOffsaletime(new Date());
        // 2.绑定领养人信息(user_id)
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        pet.setUser_id(user.getId());
        // 更新宠物信息
        petMapper.update(pet);
        // 3.@TODO 生成领养订单

        // 4.@TODO 支付订单完成支付

    }
}
